/*********
 * 场景管理类
 * @author wzj
 * 
 */

class SenceManage {
	//静态属性
	static _self;	//存储单例对象的容器
	static create(stage=null) {
		if (!SenceManage._self) {
			SenceManage._self = new SenceManage(stage)
		}
			
		return SenceManage._self;
	}
	public constructor(stage) {
		this._stage = stage
		// console.log(RES)
	}
	/**加载场景**/
	private _senceName;
	private _nextSence;	//保存下一个场景的类对象
	private _stage;
	private _curSence	//当前场景实例化对象
	private _callback 	//保存加载完成后的回调操作
	public loadSence(senceName, curSence, nextSence, callback = null) {
		this._nextSence = nextSence;
		this._curSence = curSence;
		this._senceName = senceName
		RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
		RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
		RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
		RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
		RES.loadGroup(senceName)//开始加载对应组的素材
	}
	private onResourceLoadComplete(event: RES.ResourceEvent): void {
		if (event.groupName == this._senceName) {
			RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
			RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
			RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
			RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this);
			//创建新场景，并移除旧场景，最后执行回调函数

			var newSence = new this._nextSence();
			newSence.x = this._stage.$stageWidth * .5;
			newSence.y = this._stage.$stageHeight * .5;
			newSence.scaleX = 0;
			newSence.scaleY = 0;
			newSence.anchorOffsetX = this._stage.$stageWidth * .5;
			newSence.anchorOffsetY = this._stage.$stageHeight * .5;
			this._stage.addChild(newSence);
			egret.Tween.get(newSence).to({ scaleX: 1, scaleY: 1}, 1000).call(function () {
				if (this._curSence != null) {
					this._stage.removeChild(this._curSence);
				}
				this.callback ? this.callback() : "";
			}.bind(this))
		}
	}
	private onItemLoadError(event: RES.ResourceEvent): void {
		console.warn("Url:" + event.resItem.url + " has failed to load");
	}

	private onResourceLoadError(event: RES.ResourceEvent): void {
		console.warn("Group:" + event.groupName + " has failed to load");
		this.onResourceLoadComplete(event);
	}

	private onResourceProgress(event: RES.ResourceEvent): void {
		if (event.groupName == "icons") {
		}
	}
}


